#!/bin/bash
{
	#////////////////////////////////////
	# DietPi Cron.Daily script
	#
	#////////////////////////////////////
	#
	# Info:
	# - Location: /etc/cron.daily/dietpi
	#
	#////////////////////////////////////

	#----------------------------------------------------------------
	# Main Loop
	#----------------------------------------------------------------
	# Sync system time if mode 2 (daily) is detected
	grep -q '^[[:blank:]]*CONFIG_NTP_MODE=2' /boot/dietpi.txt && /boot/dietpi/func/run_ntpd 1
	#----------------------------------------------------------------
	# Check for DietPi and/or APT updates
	APT_UPDATE_MODE=$(sed -n '/^[[:blank:]]*CONFIG_CHECK_APT_UPDATES=/{s/^[^=]*=//p;q}' /boot/dietpi.txt)
	if grep -q '^[[:blank:]]*CONFIG_CHECK_DIETPI_UPDATES=1' /boot/dietpi.txt
	then
		/boot/dietpi/dietpi-update 2
		[[ $APT_UPDATE_MODE == 2 && -f '/run/dietpi/.update_available' ]] && G_AGUP -f

	elif [[ $APT_UPDATE_MODE != 0 ]]
	then
		G_AGUP -f
	fi
	# Apply APT upgrades if chosen and available
	if [[ $APT_UPDATE_MODE == 2 && -f '/run/dietpi/.apt_updates' ]]
	then
		apt-get -qq upgrade &> /var/tmp/dietpi/logs/dietpi-upgrade_apt.log
		# Assure all services are up since APT upgrades might stop them
		/boot/dietpi/dietpi-services start
	fi
	#----------------------------------------------------------------
	# Refresh DietPi MOTD
	if [[ ! -f '/boot/dietpi/.dietpi-banner' ]] || grep -q '^[[:blank:]]*aENABLED\[12\]=1' /boot/dietpi/.dietpi-banner
	then
		[[ -f '/run/dietpi/.dietpi_motd' ]] && rm /run/dietpi/.dietpi_motd
		curl -sSfL https://dietpi.com/motd -o /run/dietpi/.dietpi_motd
	fi
	#----------------------------------------------------------------
	# DietPi-Sync daily
	if [[ -f '/boot/dietpi/.dietpi-sync_settings' ]] && grep -q '^[[:blank:]]*SYNC_CRONDAILY=1' /boot/dietpi/.dietpi-sync_settings
	then
		/boot/dietpi/dietpi-sync 1
	fi
	#----------------------------------------------------------------
	exit
	#----------------------------------------------------------------
} > /dev/null
